package com.weishi.project.training.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.enums.RedisConstants;
import com.weishi.common.enums.TrainingProgramEnum;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.redis.RedisCache;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.api.vo.ChannelAchievementVo;
import com.weishi.project.api.vo.TrainingAchievementMaxVo;
import com.weishi.project.api.vo.appvo.SubsectionDTO;
import com.weishi.project.sport.movement.vo.TrainingVO;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.mapper.TrainingGroupChannelMapper;
import com.weishi.project.training.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 训练小组航道Service业务层处理
 */
@Service
public class TrainingGroupChannelServiceImpl extends ServiceImpl<TrainingGroupChannelMapper, TrainingGroupChannel> implements ITrainingGroupChannelService {

    @Resource
    private TrainingGroupChannelMapper trainingGroupChannelMapper;

    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 分段成绩 接口
     */
    @Autowired
    private IDynamometerSubsectionService dynamometerSubsectionService;

    /**
     * 训练课 接口
     */
    @Autowired
    private ITrainingDayService trainingDayService;

    /**
     * 水上分段 接口
     */
    @Autowired
    private IHeartRateCountService heartRateCountService;

    @Autowired
    private IHeartRateRecordService heartRateRecordService;

    /**
     * 分段成绩接口
     */
    @Autowired
    private IDynamometerRankingService dynamometerRankingService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 查询训练小组航道列表
     */
    @Override
    public List<TrainingGroupChannel> selectTrainingGroupChannelList(TrainingGroupChannel trainingGroupChannel) {
        List<TrainingGroupChannel> trainingGroupChannels = trainingGroupChannelMapper.selectTrainingGroupChannelList(trainingGroupChannel);
        return trainingGroupChannels;
    }

    @Override
    public TrainingGroupChannel getTrainingGroupChannelDetails(int id) {
        return trainingGroupChannelMapper.getTrainingGroupChannelDetails(id);
    }

    @Override
    public void updateTrainingGroupChannelById(TrainingGroupChannel trainingGroupChannel) {
        trainingGroupChannelMapper.updateTrainingGroupChannelById(trainingGroupChannel);
    }

    @Override
    public List<TrainingGroupChannel> getChannelNameList() {
        return trainingGroupChannelMapper.getChannelNameList();
    }

    @Override
    public int getChannelIdByGroupIdAndChannelNameAndBatch(Map<String, Object> map) {
        return trainingGroupChannelMapper.getChannelIdByGroupIdAndChannelNameAndBatch(map);
    }

    @Override
    public List<TrainingGroupChannel> getTrainingGroupChannelByWeekIdAndTrainingDayId(Map<String, Object> map) {
        return trainingGroupChannelMapper.getTrainingGroupChannelByWeekIdAndTrainingDayId(map);
    }

    @Override
    public List<TrainingGroupChannel> getTrainingGroupChannelByGroupId(int groupId, boolean sportmanNameFlag) {
        Map<String, Object> map = new HashMap<>();
        map.put("groupId", groupId);
        List<TrainingGroupChannel> channels = trainingGroupChannelMapper.getTrainingGroupChannelByGroupId(map);
        if (sportmanNameFlag) {
            for (TrainingGroupChannel channel : channels) {
                List<TrainingAchievementMaxVo> trainingAchievementList = trainingAchievementService.selectTrainingAchievementListByChannelId(channel.getId());
                List<String> list = channel.getSportsmanName();
                if (list == null) {
                    list = new ArrayList<>();
                    channel.setSportsmanName(list);
                }
                for (TrainingAchievementMaxVo achievement : trainingAchievementList) {
                    list.add(achievement.getName());
                }
            }
        }
        return channels;
    }

    @Override
    public List<TrainingGroupChannel> getTrainingGroupChannelAndAchievementByGroupId(int groupId) {
        Map<String, Object> map = new HashMap<>();
        map.put("groupId", groupId);
        List<TrainingGroupChannel> channels = trainingGroupChannelMapper.getTrainingGroupChannelByGroupId(map);
        List<TrainingAchievement> achievements = trainingAchievementService.trainingAchievementList(map);
        Map<Integer,List<TrainingAchievement>> achievementsMap = new HashMap<>();
        for(TrainingAchievement achievement : achievements){
            List<TrainingAchievement> list = achievementsMap.get(achievement.getChannelId());
            if(list==null){
                list = new ArrayList<>();
                achievementsMap.put(achievement.getChannelId(),list);
            }
            list.add(achievement);
        }
        for(TrainingGroupChannel channel : channels){
            channel.setPerson(achievementsMap.get(channel.getId()));
        }
        return channels;
    }

    @Override
    @Transactional
    public void updateTrainingGroupChannelList(TrainingGroupChannel trainingGroupChannel) {
        trainingGroupChannelMapper.updateTrainingGroupChannelList(trainingGroupChannel);
        if (trainingGroupChannel.getPerson() != null && trainingGroupChannel.getPerson().size() > 0) {
            trainingAchievementService.deleteTrainingAchievementByChannelId(trainingGroupChannel.getId());
            for (TrainingAchievement trainingAchievement : trainingGroupChannel.getPerson()) {
                trainingAchievement.setChannelId(trainingGroupChannel.getId());
                trainingAchievementService.saveOrUpdate(trainingAchievement);
            }
        }
    }

    @Override
    public boolean selectAchievementIsNull(Map<String, Object> map) {
        return trainingGroupChannelMapper.selectAchievementIsNull(map) > 0;
    }

    @Override
    public List<ChannelAchievementVo> queryChannelAchievement(Map<String, Object> map) {
        List<ChannelAchievementVo> retList = trainingGroupChannelMapper.queryChannelAchievement(map);
        for (ChannelAchievementVo vo : retList) {
            int propellerFrequencyTotal = 0;
            int propellerFrequencyAvg = 0;
            if (StringUtils.isNotEmpty(vo.getSegmentPropellerFrequency())) {
                String[] propellerFrequencys = vo.getSegmentPropellerFrequency().trim().split(" ");
                for (String pp : propellerFrequencys) {
                    int aa;
                    try {
                        aa = Integer.parseInt(pp);
                    } catch (NumberFormatException e) {
                        aa = 0;
                    }
                    propellerFrequencyTotal += aa;
                }
                if (propellerFrequencys.length > 0)
                    propellerFrequencyAvg = propellerFrequencyTotal / propellerFrequencys.length;
            }
            vo.setPropellerFrequency(propellerFrequencyAvg);
        }
        return retList;
    }

    @Override
    public List<TrainingGroupChannel> qryBestTop10(Map<String, Object> params, boolean setPerson) {
        List<TrainingGroupChannel> list = trainingGroupChannelMapper.qryBestTop10(params);
        if (setPerson) {
            for (TrainingGroupChannel trainingGroupChannel : list) {
                TrainingAchievement param = new TrainingAchievement();
                param.setChannelId(trainingGroupChannel.getId());
                List<TrainingAchievement> list1 = trainingAchievementService.selectTrainingAchievementList1(param);
                trainingGroupChannel.setPerson(list1);
            }
        }
        return list;
    }

    @Override
    public TrainingGroupChannel getTrainingGroupChannelAndAchievement(Integer channelId) {
        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelMapper.getTrainingGroupChannelDetails(channelId);
        TrainingAchievement params = new TrainingAchievement();
        params.setChannelId(channelId);

        List<TrainingAchievement> trainingAchievementList = trainingAchievementService.selectTrainingAchievementList1(params);
        for (TrainingAchievement achievement : trainingAchievementList) {
            Sportsman s = this.sportsmanService.qrySportsmanByCache(achievement.getSportsmanId());
            achievement.setSportsmanName(s.getName());

            // 判断水上或者陆上
            if (trainingGroupChannel.getFirstLevel().equals("special_training_water")) {
                // 水上
                trainingGroupChannel.setSegmentPropellerFrequency(trainingGroupChannel.getPropellerFrequency());
                // 心率
                achievement.setSegmentHeartRate(achievement.getHeartRate());

            } else {
                // 陆上
                /**
                 * 查询 分段数据
                 */
                /*List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                        .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                                .eq(DynamometerSubsection::getSportsmanId , achievement.getSportsmanId())
                                .eq(DynamometerSubsection::getGroupId , achievement.getGroupId())
                                .eq(DynamometerSubsection::getTrainingDayId , achievement.getTrainingDayId()));

                // 速度
                double averageSpeed = 0;
                // 取最大心率 计算平均心率
                Integer averageHeartRate = 0;
                // 平均功率
                Integer averagePower = 0;
                // 平均桨频
                Integer averagePropellerFrequency = 0;
                // 分段心率
                String segmentHeartRate = "";
                // 分段桨频
                String segmentPropellerFrequency = "";
                // 分段功率
                String segmentPower = "";
                // 分段瓦特
                String segmentWatt = "";
                // 分段时长
                String segmentLengthTime = "";
                // 分段距离
                String segmentMileage = "";
                if(dynamometerSubsectionList.size() > 0){
                    for(int i = 0; i<dynamometerSubsectionList.size() ;i++){
                        if(StringUtils.isNotNull(dynamometerSubsectionList.get(i).getLengthTime())){
                            if(dynamometerSubsectionList.get(i).getSpeed()!=null)averageSpeed += dynamometerSubsectionList.get(i).getSpeed();
                        }
                        if(StringUtils.isNotNull(dynamometerSubsectionList.get(i).getHeartRate())){
                            averageHeartRate+=dynamometerSubsectionList.get(i).getHeartRate();
                        }
                        // 存入桨数
                        trainingGroupChannel.setPulpNumber(dynamometerSubsectionList.get(i).getPulpNumber());
                        trainingGroupChannel.setPower(dynamometerSubsectionList.get(0).getPower());
                        // 计算平均功率
                        averagePower += StringUtils.turnSecond(dynamometerSubsectionList.get(i).getPower());
                        // 存入桨频
                        trainingGroupChannel.setPropellerFrequency(dynamometerSubsectionList.get(i).getPropellerFrequency());
                        // 计算平均桨频
                        averagePropellerFrequency += Integer.parseInt(dynamometerSubsectionList.get(i).getPropellerFrequency());
                        // 峰力
                        trainingGroupChannel.setPeakForce(String.valueOf(dynamometerSubsectionList.get(i).getPeakForce()));
                        // 均力
                        trainingGroupChannel.setAverageForce(String.valueOf(dynamometerSubsectionList.get(i).getAverageForce()));
                        // 平均瓦特
                        trainingGroupChannel.setAverageWatt(String.valueOf(Integer.parseInt(dynamometerSubsectionList.get(0).getWatt())));
                        // 分段心率
                        segmentHeartRate += dynamometerSubsectionList.get(i).getHeartRate() + " ";
                        // 分段桨频
                        segmentPropellerFrequency += dynamometerSubsectionList.get(i).getPropellerFrequency() + " ";
                        // 分段功率
                        segmentPower += dynamometerSubsectionList.get(i).getPower() + " ";
                        // 分段瓦特
                        segmentWatt += dynamometerSubsectionList.get(i).getWatt() + " ";
                        // 速度
                        trainingGroupChannel.setSpeed(dynamometerSubsectionList.get(i).getSpeed());
                        if(dynamometerSubsectionList.get(i).getTrainingMode() == 0){
                            // 分段时长
                            segmentLengthTime += dynamometerSubsectionList.get(i).getLengthTime() + " ";
                            // 存储分段成绩
                            String segmentedTiming = segmentLengthTime.substring(0 , segmentLengthTime.length()-1);
                            trainingGroupChannel.setSegmentedTiming(segmentedTiming);
                            // 分段距离
                            segmentMileage += dynamometerSubsectionList.get(i).getMileage() + " ";
                            trainingGroupChannel.setSegmentMileage(segmentMileage);
                        }else{
                            // 分段距离
                            segmentMileage += dynamometerSubsectionList.get(i).getMileage() + " ";
                            String segmentedTiming = segmentMileage.substring(0 , segmentMileage.length()-1);
                            trainingGroupChannel.setSegmentedTiming(segmentedTiming);
                            trainingGroupChannel.setSegmentMileage(segmentMileage);
                        }
                    }
                    Double averageSpeed2 = averageSpeed/dynamometerSubsectionList.size();
                    Long a =Math.round(averageSpeed2);
                    Double c = a.doubleValue();
                    trainingGroupChannel.setAverageSpeed(c.toString());
                    // 存储平均心率
                    if(averageHeartRate>0)trainingGroupChannel.setAverageHeartRate(averageHeartRate);
                    // 存储平均功率
                    Integer averagePowers = averagePower/dynamometerSubsectionList.size();
                    if(StringUtils.isNotNull(StringUtils.millisecondRotationTime(averagePowers)))trainingGroupChannel.setAveragePower(StringUtils.millisecondRotationTime(averagePowers));
                    // 平均桨频
                    trainingGroupChannel.setAveragePropellerFrequency(averagePropellerFrequency/dynamometerSubsectionList.size());
                    // 存储分段心率
                    achievement.setSegmentHeartRate(segmentHeartRate.substring(0 , segmentHeartRate.length()-1));
                    // 存储分段桨频
                    trainingGroupChannel.setSegmentPropellerFrequency(segmentPropellerFrequency.substring(0 , segmentPropellerFrequency.length()-1));
                    // 存储分段功率
                    trainingGroupChannel.setSegmentPower(segmentPower.substring(0 , segmentPower.length()-1));
                    // 存储分段瓦特
                    trainingGroupChannel.setSegmentWatt(segmentWatt.substring(0 , segmentWatt.length()-1));
                    // 存储 训练课 id
                    trainingGroupChannel.setTrainingDayId(achievement.getTrainingDayId());
                }*/


            }
        }
        trainingGroupChannel.setPerson(trainingAchievementList);

        return trainingGroupChannel;
    }

    @Override
    @Transactional
    public boolean add(TrainingGroupChannel trainingGroupChannel) {
        boolean ret = this.saveOrUpdate(trainingGroupChannel);
        if (trainingGroupChannel.getPerson() != null && trainingGroupChannel.getPerson().size() > 0) {
            for (TrainingAchievement trainingAchievement : trainingGroupChannel.getPerson()) {
                trainingAchievement.setChannelId(trainingGroupChannel.getId());
                trainingAchievement.setCtime(new Date());
                // 接收 分段心率
                List<TrainingAchievement> segmentHeartRate = trainingGroupChannel.getPerson();
                String segmentHeartRate2 = "";
                for (int i = 0; i < segmentHeartRate.size(); i++) {
                    segmentHeartRate2 += segmentHeartRate.get(i).getSegmentHeartRate() + " ";
                    trainingAchievement.setSportsmanName(sportsmanService.getById(segmentHeartRate.get(i).getSportsmanId()).getName());
                }
                trainingAchievement.setHeartRate(segmentHeartRate2); // 存储分段心率
                trainingAchievementService.saveOrUpdate(trainingAchievement);
            }
        }
        return ret;
    }

    @Override
    public boolean removeByIds(List<Integer> idList) {
        boolean ret = false;
        for (Integer channelId : idList) {
            ret = removeById(channelId);
        }
        return ret;
    }

    /**
     * 删除训练航道同步删除训练成绩的相关数据
     *
     * @param channelId
     * @return
     */
    @Transactional
    @Override
    public boolean removeById(Integer channelId) {
        TrainingAchievement params = new TrainingAchievement();
        params.setChannelId(channelId);
        List<TrainingAchievement> trainingAchievements = trainingAchievementService.selectTrainingAchievementList1(params);
        List<Integer> achievementIds = new ArrayList<>();
        for (TrainingAchievement trainingAchievement : trainingAchievements) {
            achievementIds.add(trainingAchievement.getId());
        }
        trainingAchievementService.removeByIds(achievementIds);
        int ret = trainingGroupChannelMapper.deleteById(channelId);
        return ret == 0 ? false : true;
    }


    /**
     * PC 端 -- 查询航道水上陆上分段数据
     */
    @Transactional
    @Override
    public AjaxResult getSubsection(JSONObject jsonObject) {
        TrainingDay trainingDay = trainingDayService.getById(Integer.parseInt(jsonObject.get("trainingDayId").toString()));
        List<SubsectionDTO> subsectionDTOList = new ArrayList<>();
        if (jsonObject.get("firstLevel").equals(TrainingProgramEnum.WATERPROJECT.getKey())) {
            // 获取水上数据
            List<HeartRateCount> heartRateCountList = heartRateCountService
                    .list(Wrappers.<HeartRateCount>lambdaQuery()
                            .eq(HeartRateCount::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                            .eq(HeartRateCount::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString()))
                            .orderByAsc(HeartRateCount::getStage));
            if (heartRateCountList.size() > 0) heartRateCountList.forEach(p -> {
                SubsectionDTO subsectionDTO = new SubsectionDTO();
                StringUtils.copyProperties(p, subsectionDTO);
                subsectionDTO.setRowingKilometers(p.getTotalDistance());
                subsectionDTO.setAchievement(p.getPointAchievement());
                subsectionDTO.setMileage(p.getTotalDistance());
                subsectionDTO.setLengthTime(p.getPointAchievement());
                subsectionDTO.setSpeed(p.getShipSpeed());
                subsectionDTO.setTrainingMode(trainingDay.getTrainingMode());

                // 查询这条船上的所有人
                List<SubsectionDTO.Person> personList = new ArrayList<>();
                List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                        .list(Wrappers.<HeartRateRecord>lambdaQuery()
                                .eq(HeartRateRecord::getHeartRateCountId, p.getId()));
                if (heartRateRecordList.size() > 0) heartRateRecordList.forEach(h -> {
                    SubsectionDTO.Person person = new SubsectionDTO.Person();
                    StringUtils.copyProperties(h, person);
                    person.setHeartRate(h.getHeartRateAvg());
                    personList.add(person);
                });
                subsectionDTO.setPerson(personList);
                subsectionDTOList.add(subsectionDTO);
            });
            return AjaxResult.success(subsectionDTOList);
        } else {
            // 获取陆上数据
            List<DynamometerSubsection> dynamometerSubsections = dynamometerSubsectionService
                    .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                            .eq(DynamometerSubsection::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString()))
                            .eq(DynamometerSubsection::getGroupId, Integer.parseInt(jsonObject.get("groupId").toString()))
                            .orderByAsc(DynamometerSubsection::getSegmentNumber));
            // 存储分段成绩
            List<String> segmentedTiming = new ArrayList<>();
            // 存储分段里程
            List<Double> segmentedMileage = new ArrayList<>();
            if (dynamometerSubsections.size() > 0) dynamometerSubsections.forEach(p -> {
                segmentedTiming.add(p.getLengthTime());
                segmentedMileage.add(p.getMileage());
            });
            int size = dynamometerSubsections.size();
            // 存储分段成绩2
            List<String> segmentedTimingList = new ArrayList<>();
            // 存储分段里程 2
            List<Double> segmentedMileageList = new ArrayList<>();
            for (int j = 0; j < dynamometerSubsections.size(); j++) {
                size--;
                List<SubsectionDTO.Person> personList = new ArrayList<>();
                SubsectionDTO subsectionDTO = new SubsectionDTO();
                SubsectionDTO.Person person = new SubsectionDTO.Person();
                StringUtils.copyProperties(dynamometerSubsections.get(j), subsectionDTO);
                subsectionDTO.setRowingKilometers(dynamometerSubsections.get(j).getMileage());
                if (trainingDay.getTrainingMode() == 0) {
                    // 减时间
                    if (size == 1) {
                        Long lengthTime3 = StringUtils.turnSecond(segmentedTiming.get(size));
                        Long lengthTime2 = StringUtils.turnSecond(segmentedTiming.get(size - 1));
                        Long lengthTime = lengthTime3 - lengthTime2;
                        segmentedTimingList.add(StringUtils.millisecondRotationTime(lengthTime));
                        subsectionDTO.setLengthTime(StringUtils.millisecondRotationTime(lengthTime));
                    } else if (size == 0) {
                        subsectionDTO.setLengthTime(segmentedTiming.get(0));
                        segmentedTimingList.add(segmentedTiming.get(0));
                    } else if (size > 1) {
                        Long lengthTime3 = StringUtils.turnSecond(segmentedTiming.get(size));
                        Long lengthTime2 = StringUtils.turnSecond(segmentedTiming.get(size - 1));
                        Long lengthTime = lengthTime3 - lengthTime2;
                        System.out.println();
                        subsectionDTO.setLengthTime(StringUtils.millisecondRotationTime(lengthTime));
                        segmentedTimingList.add(StringUtils.millisecondRotationTime(lengthTime));
                    }
                } else if (trainingDay.getTrainingMode() == 1) {
                    // 减距离
                    if (size == 1) {
                        Double mileage3 = segmentedMileage.get(size);
                        Double mileage2 = segmentedMileage.get(size - 1);
                        Double mileage = mileage3 - mileage2;
                        segmentedMileageList.add(mileage);
                        subsectionDTO.setMileage(mileage);
                    } else if (size == 0) {
                        subsectionDTO.setMileage(segmentedMileage.get(0));
                        segmentedMileageList.add(segmentedMileage.get(0));
                    } else if (size > 1) {
                        Double mileage3 = segmentedMileage.get(size);
                        Double mileage2 = segmentedMileage.get(size - 1);
                        Double mileage = mileage3 - mileage2;
                        System.out.println();
                        segmentedMileageList.add(mileage);
                        subsectionDTO.setMileage(mileage);
                    }
                }
                subsectionDTO.setStage(dynamometerSubsections.get(j).getSegmentNumber());
                person.setSportsmanId(dynamometerSubsections.get(j).getSportsmanId());
                person.setHeartRate(dynamometerSubsections.get(j).getHeartRate());
                personList.add(person);
                subsectionDTO.setPerson(personList);
                subsectionDTOList.add(subsectionDTO);
            }

            List<SubsectionDTO> list = new ArrayList<>();
            int index = subsectionDTOList.size();
            for (int k = 0; k < subsectionDTOList.size(); k++) {
                index--;
                SubsectionDTO subsectionDTO = new SubsectionDTO();
                StringUtils.copyProperties(subsectionDTOList.get(k), subsectionDTO);
                if (trainingDay.getTrainingMode() == 0) {
                    subsectionDTO.setLengthTime(segmentedTimingList.get(index));
                } else if (trainingDay.getTrainingMode() == 1) {
                    subsectionDTO.setMileage(segmentedMileageList.get(index));
                }
                list.add(subsectionDTO);
            }
            return AjaxResult.success(list);
        }
    }


    /**
     * PC 端 -- 删除水上或者陆上分段数据
     */
    @Override
    @Transactional
    public void deleteSubsection(JSONObject jsonObject) {
        // 水上删除数据
        if (jsonObject.get("firstLevel").equals(TrainingProgramEnum.WATERPROJECT.getKey())) {
            // 1， 先删除水上分段心率，然后再删除水上分段数据
            HeartRateCount heartRateCount = heartRateCountService.getById(Integer.parseInt(jsonObject.get("id").toString()));
            // 2，查询分段心率数据
            if (StringUtils.isNotNull(heartRateCount)) {
                List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                        .list(Wrappers.<HeartRateRecord>lambdaQuery()
                                .eq(HeartRateRecord::getHeartRateCountId, heartRateCount.getId()));
                // 3，删除水上心率
                if (heartRateRecordList.size() > 0) heartRateRecordList.forEach(p -> {
                    heartRateRecordService.removeById(p.getId());
                });
                // 4，删除分段数据
                heartRateCountService.removeById(heartRateCount.getId());
            }
        } else {
            // 陆上删除数据
            dynamometerSubsectionService.removeById(Integer.parseInt(jsonObject.get("id").toString()));
        }
    }


    /**
     * PC 端 -- 清空航道下关联的数据，以及航道数据
     */
    @Override
    @Transactional
    public void emptyChannel(JSONObject jsonObject) {
        // 1,先删除航道下的成绩表，2，在清空航道里面某些数据 3，再删除分段数据，陆上再删除 tbl_dynamometer_ranking 表

        // 1,根据航道 id 查询成绩表然后删除数据 tbl_training_achievement
        List<TrainingAchievement> trainingAchievementList = trainingAchievementService
                .list(Wrappers.<TrainingAchievement>lambdaQuery().eq(TrainingAchievement::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString())));
        if (trainingAchievementList.size() > 0) trainingAchievementList.forEach(p -> {
            trainingAchievementService.removeById(p.getId());
        });

        // 清除航道数据
        this.removeById(Integer.parseInt(jsonObject.get("channelId").toString()));
       /* TrainingGroupChannel trainingGroupChannel = this.getById(Integer.parseInt(jsonObject.get("channelId").toString()));
        trainingGroupChannel.setChannelInfoStr("");
        trainingGroupChannel.setBoatType("");
        trainingGroupChannel.setAchievement("");
        trainingGroupChannel.setSegmentedTiming("");
        trainingGroupChannel.setPower("");
        trainingGroupChannel.setAverageFrequency(0.0);
        trainingGroupChannel.setWatt("");
        trainingGroupChannel.setPropellerFrequency("");
        trainingGroupChannel.setMaxSpeed("");
        trainingGroupChannel.setAverageSpeed("");
        trainingGroupChannel.setAchievementMs(0);
        trainingGroupChannel.setId(Integer.parseInt(jsonObject.get("channelId").toString()));
        this.updateById(trainingGroupChannel);*/

        // 删除水上或者陆上数据
        // 水上删除数据
        if (jsonObject.get("firstLevel").equals(TrainingProgramEnum.WATERPROJECT.getKey())) {
            // 1， 先删除水上分段心率，然后再删除水上分段数据
            List<HeartRateCount> heartRateCountList = heartRateCountService
                    .list(Wrappers.<HeartRateCount>lambdaQuery()
                            .eq(HeartRateCount::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString())));
            if (heartRateCountList.size() > 0) heartRateCountList.forEach(p -> {
                List<HeartRateRecord> heartRateRecordList = heartRateRecordService
                        .list(Wrappers.<HeartRateRecord>lambdaQuery()
                                .eq(HeartRateRecord::getHeartRateCountId, p.getId()));
                if (heartRateRecordList.size() > 0) heartRateRecordList.forEach(c -> {
                    // 删除心率
                    heartRateRecordService.removeById(c.getId());
                });
                // 删除分段
                heartRateCountService.removeById(p.getId());
            });

        } else {
            // 陆上删除数据
            List<DynamometerSubsection> dynamometerSubsectionList = dynamometerSubsectionService
                    .list(Wrappers.<DynamometerSubsection>lambdaQuery()
                            .eq(DynamometerSubsection::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString())));
            if (dynamometerSubsectionList.size() > 0) dynamometerSubsectionList.forEach(p -> {
                dynamometerSubsectionService.removeById(p.getId());
            });
            // 删除 tbl_dynamometer_ranking 数据
            List<DynamometerRanking> dynamometerRankingList = dynamometerRankingService
                    .list(Wrappers.<DynamometerRanking>lambdaQuery()
                            .eq(DynamometerRanking::getChannelId, Integer.parseInt(jsonObject.get("channelId").toString())));
            if (dynamometerRankingList.size() > 0) dynamometerRankingList.forEach(p -> {
                dynamometerRankingService.removeById(p.getId());
            });
        }


    }

    @Override
    public int getChannelStatus(Integer channelId) {
        Integer status = redisCache.getCacheObject(RedisConstants.Channel_Training_Status+channelId);
        return status;
    }

    @Override
    public int setChannelStatus(Integer channelId,Integer status) {
        redisCache.setCacheObject(RedisConstants.Channel_Training_Status+channelId,status,1, TimeUnit.HOURS);
        return 0;
    }



    /**
     * 根据 小组id 和用户 id 查询有没有在训练
     */
    @Override
    public List<TrainingVO> getOneTrainingVO(Integer groupId, Integer userId) {
        return trainingGroupChannelMapper.getOneTrainingVO(groupId , userId);
    }




}